package com.spingcloud.demo.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
//刷新，从新注入
@RefreshScope
public class PreFilter extends ZuulFilter{

    @Value("${token}")
    private boolean token;

    @Override
    public String filterType() {//过滤器类型
        return FilterConstants.PRE_TYPE;
//        return "pre";
    }

    //优先级
    @Override
    public int filterOrder() {//同类型之间的优先级，数越大越低
        return 0;
    }

    //是否参与网管检查
    @Override
    public boolean shouldFilter() {//过滤器是否起作用
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx= RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

//        String key = request.getParameter("key");
//        System.out.println(key + " access filter 1");
//        ctx.set("thirdfilter",true);
//        if("1".equals(key)) {
//            ctx.setSendZuulResponse(false);
//        }else if("".equals(key)){
//            ctx.set("thirdfilter",false);
//        }
//        return null;
        System.out.println("==============="+token+"=================");
        if(token) {
        String token = request.getHeader("token");
            if(!StringUtils.isNotEmpty(token)){
                //设置false，后面不用路由转发
                ctx.setSendZuulResponse(false);
                //返回错误代码
                ctx.setResponseStatusCode(401);
                ctx.setResponseBody("{\"msg\":\"401, access without permission , pls login first.\"}");
                return "access denied";
            }
        }
        return "pass";
    }
}
